package com.smallsoft.helper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import com.smallsoft.beans.Category;
import com.smallsoft.beans.Content;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper{

	private static String TAG = "DataBaseHelper";
	private static String DB_NAME = "phongtucvietnam.db";
	//private static final String DB_PATH = "/data/data/phongtucvietnam";
	private static String DB_PATH = "";
	private SQLiteDatabase mDataBase;
	private Context mContext;
	private DatabaseHelper dbHelper;
	
	
	public DatabaseHelper(Context context) {
		super(context, DB_NAME, null, 1);
		this.mContext = context;
		if(android.os.Build.VERSION.SDK_INT >= 17){
		       DB_PATH = context.getApplicationInfo().dataDir + "/databases/";         
	    }
	    else
	    {
	       DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
	    }
		
		onCreate();
	}
	
	public void onCreate(){
		 boolean dbExist = checkDataBase();
		 if (dbExist) {
	            openDatabase(); 
	        } else {
	            try {
					createDatabase();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}
	
	public void createDatabase() throws IOException
	{
	    //If database not exists copy it from the assets

	    boolean dbExist = checkDataBase();
	    if(!dbExist)
	    {
	        this.getReadableDatabase();
	        this.close();
	        try 
	        {
	            //Copy the database from assests
	            copyDataBase();
	            Log.e(TAG, "createDatabase database created");
	        } 
	        catch (IOException mIOException) 
	        {
	            throw new Error("ErrorCopyingDataBase");
	        }
	    }
	}
	    //Check that the database exists here: /data/data/your package/databases/Da Name
	    private boolean checkDataBase()
	    {
	        File dbFile = new File(DB_PATH + DB_NAME);
	        //Log.v("dbFile", dbFile + "   "+ dbFile.exists());
	        return dbFile.exists();
	    }

	    //Copy the database from assets
	    private void copyDataBase() throws IOException
	    {
	        InputStream mInput = mContext.getAssets().open(DB_NAME);
	        String outFileName = DB_PATH + DB_NAME;
	        OutputStream mOutput = new FileOutputStream(outFileName);
	        byte[] mBuffer = new byte[1024];
	        int mLength;
	        while ((mLength = mInput.read(mBuffer))>0)
	        {
	            mOutput.write(mBuffer, 0, mLength);
	        }
	        mOutput.flush();
	        mOutput.close();
	        mInput.close();
	    }

	    //Open the database, so we can query it
	    public boolean openDatabase() throws SQLException
	    {
	        String mPath = DB_PATH + DB_NAME;
	        mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
	        return mDataBase != null;
	    }

	    @Override
	    public synchronized void close() 
	    {
	        if(mDataBase != null)
	            mDataBase.close();
	        super.close();
	    }
	    
	    public ArrayList<Category> getCategory (Context context){
	    	ArrayList<Category> categories = new ArrayList<Category>();
	    	dbHelper = new DatabaseHelper(context);
	    	String sql ="SELECT * FROM category";
	    	SQLiteDatabase db = dbHelper.getReadableDatabase();
	    	Cursor cursor = db.rawQuery(sql, null);
	    	cursor.moveToFirst();
	    	do{
	    		int catId = cursor.getInt(0);
	    		String name = cursor.getString(1);
	    		Category category = new Category();
	    		category.setId(catId);
	    		category.setName(name);
	    		categories.add(category);
	    	}while(cursor.moveToNext());
	    	cursor.close();
	        db.close();
	    	return categories;
	    }
	    
	    
	    public ArrayList<Content> getContent(Context context, int catId){
	    	ArrayList<Content> contents = new ArrayList<Content>();
	    	dbHelper = new DatabaseHelper(context);
	    	String sql ="SELECT * FROM phongtuc WHERE catId = " + catId;
	    	SQLiteDatabase db = dbHelper.getReadableDatabase();
	    	Cursor cursor = db.rawQuery(sql, null);
	    	cursor.moveToFirst();
	    	do{
	    		int id = cursor.getInt(0);
	    		String title = cursor.getString(1);
	    		String c = cursor.getString(2);
	    		int catID = cursor.getInt(3); 
	    		Content content = new Content();
	    		content.setId(id);
	    		content.setTitle(title);
	    		content.setContent(c);
	    		content.setCatId(catID);
	    		contents.add(content);
	    	}while(cursor.moveToNext());
	    	cursor.close();
	        db.close();
	    	return contents;
	    }

}
